<template>
  <el-dialog
    width="80%"
    v-model="visible"
    :before-close="beforeClose"
    append-to-body
    v-if="config"
  >
    <nv-filter :config="config" ref="nvFilter" @define-event="handleEvent($event)" v-if="config"></nv-filter>
    <span slot="footer" class="dialog-footer">
        <el-button @click="cancelClose()">取消</el-button>
        <el-button type="primary"  @click="confirmClose()">确认</el-button>
      </span>
  </el-dialog>
</template>

<script>
import NvFilter from './NvFilter'
import ConstDef from '../../js/ConstDef'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
export default {
  name: 'NvFilterDialog',
  components: { NvFilter },
  setup(props) {
    const visible = ref(false);
    const config = ref(null);
    const chooseCb = ref(null);
    const chooseType = ref('');
    function showSingleChoose(filterConfig, callback) {
      config.value = filterConfig;
      chooseCb.value = callback;
      visible.value = true;
      chooseType.value = 'single';
    }

    function showMultipleChoose(filterConfig, callback) {
      config.value = filterConfig;
      chooseCb.value = callback;
      visible.value = true;
      chooseType.value = 'multiple';
    }

    function showImmediateChoose(filterConfig, callback) {
      config.value = filterConfig;
      chooseCb.value = callback;
      visible.value = true;
      chooseType.value = 'immediate';
    }

    return {
      visible,
      config,
      chooseType,
      showSingleChoose,
      showMultipleChoose,
      showImmediateChoose,
      chooseCb
    }
  },
  methods: {
    beforeClose(next) {
      this.config = null;
      this.chooseCb = null;
      next();
    },
    cancelClose() {
      this.visible = false;
    },
    confirmClose() {
      if (this.chooseType === 'immediate') {
        this.cancelClose();
        return;
      }
      const selectedNvs = this.$refs.nvFilter.getSelectedNvs();
      if (selectedNvs.length === 0) {
        ElMessage({
          type: 'error',
          message: '请选择表格中的行!'
        })
        return;
      }
      if (selectedNvs.length > 1) {
        ElMessage({
          type: 'error',
          message: '只能选择一行'
        })
        return;
      }

      if (this.chooseType === 'single') {
        this.chooseCb(selectedNvs[0]);
      } else if (this.chooseType === 'multiple') {
        this.chooseCb(selectedNvs);
      }
      this.visible = false;
    },
    handleEvent(event) {
      const fvData = event.fvData;
      const functionCode = fvData.fdLayout.functionCode;
      if (functionCode === ConstDef.FUNCTION_CODE_COMMIT_CHOOSE) {
        this.doChoose(fvData);
      }
    },
    doChoose(fvData) {
      this.chooseCb(fvData.getNv());
    }
  }
}
</script>

<style scoped>

</style>
